﻿using System;

namespace Red.Launcher.ViewModels.Workspaces.Database.Sql
{
    public partial class Select
    {
        /// <summary>
        /// Represents a column or value in a database table
        /// </summary>
        public class Column : IAlias, ISqlDeclaration, ISql
        {
            /// <summary>
            /// The name of the column, as defined in the database
            /// </summary>
            public string Name { get; set; }

            /// <summary>
            /// A function to apply to the value
            /// </summary>
            public string Function { get; set; }

            /// <summary>
            /// The table/join/other where this value can be found
            /// </summary>
            public IAlias Source { get; set; }

            /// <summary>
            /// A custom name by which to reference this value
            /// </summary>
            public string Alias { get; set; }

            /// <summary>
            /// This is the SQL that goes between "SELECT" and "FROM"
            /// </summary>
            public string SqlDeclaration
            {
                get
                {
                    string prefix = ( Source == null ) ? "" : Source.GetAliasPrefix();

                    if ( String.IsNullOrEmpty( Function ) )
                    {
                        return String.Format( "{0}{1}{2}", prefix, Name, this.GetAliasDeclaration() );
                    }

                    return String.Format( "{0}({1}{2}){3}", Function, prefix, Name, this.GetAliasDeclaration() );
                }
            }

            /// <summary>
            /// This is the SQL that is used when referencing the column in a WHERE clause or similar condition
            /// </summary>
            public string Sql
            {
                get
                {
                    if ( String.IsNullOrEmpty( Function ) )
                    {
                        return String.Format( "{0}{1}", Source.GetAliasPrefix(), this.GetAliasDeclaration() );
                    }

                    return this.GetAliasDeclaration();
                }
            }
        }
    }
}
